package logic

import (
	"context"
	"strings"
	"unicode/utf8"

	"book/service/sstwords/cmd/rpc/internal/svc"
	"book/service/sstwords/cmd/rpc/sstwords"

	"github.com/tal-tech/go-zero/core/logx"
	"github.com/tal-tech/go-zero/core/stringx"
)

type FilterSstwordsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFilterSstwordsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterSstwordsLogic {
	return &FilterSstwordsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FilterSstwordsLogic) FilterSstwords(in *sstwords.FilterSstwordsRequest) (*sstwords.FilterSstwordsResponse, error) {
	// 词库 - 从数据库中取数据
	var sstwords_arr = []string{
		// "演员",
	}

	rows, err := l.svcCtx.SstWordsModel.FindAllList()
	if err != nil {
		return nil, err
	}

	for _, v := range rows {
		sstwords_arr = append(sstwords_arr, v.Title)
	}

	// mask := '*'
	mask, _ := utf8.DecodeRune([]byte(in.Mask))
	filter := stringx.NewTrie(sstwords_arr, stringx.WithMask(mask)) // 默认替换为*
	safe_word, keywords, found := filter.Filter(in.Keywords)

	return &sstwords.FilterSstwordsResponse{
		SafeWord: safe_word,
		Keywords: strings.Join(keywords, ","),
		Found:    found,
	}, nil
}
